<template>
    <keep-alive :include="cacheList">
        <router-view v-if="isAlive" :key="key" />
    </keep-alive>
</template>
<script>
import { mapState, mapMutations } from 'vuex'
import { getNewTagList, getTagNavListFromLocalstorage } from '@/libs/util'

export default {
    data () {
        return {
            reloadRoute: '',
            isAlive: true
        }
    },
    provide () {
        // 父组件中通过provide来提供变量，在子组件中通过inject来注入变量。
        return {
            // 刷新当前页面
            reloadPage: this.reload,
            // 页面跳转后刷新
            nextPageReload: this.nextRouteReload
        }
    },
    watch: {
        $route (newRoute) {
            this.pushTagNav(newRoute)
            if (!this.isAlive) {
                this.reload()
            }
        }
    },
    computed: {
        ...mapState({
            tagNavList: state => state.app.tagNavList
        }),
        cacheList () {
            const reloadRoute = this.reloadRoute
            return this.tagNavList.reduce((arr, item) => {
                const { name, meta = {} } = item
                if (!meta.notCache && name && name !== reloadRoute) arr.push(name)
                return arr
            }, [])
        },
        key () {
            const { path, meta = {} } = this.$route
            return !meta.notCache ? path : new Date().getTime()
        }
    },
    created () {
        let list = getNewTagList(
            getTagNavListFromLocalstorage(),
            this.$store.state.app.homeRoute
        )
        if (this.$route.name != this.$store.state.app.homeRoute.name) {
            list = getNewTagList(list, this.$route)
        }
        this.setTagNavList(list)
    },
    methods: {
        ...mapMutations(['setTagNavList']),
        reload () {
            this.reloadRoute = this.$route.name
            this.isAlive = false
            this.$nextTick(() => {
                this.reloadRoute = ''
                this.isAlive = true
            })
        },
        nextRouteReload () {
            this.isAlive = false
        },
        pushTagNav (route) {
            const hideTags = route.meta && route.meta.hideTags
            if (!hideTags) {
                this.setTagNavList(getNewTagList(this.tagNavList, route))
            }
        }
    }
}
</script>
